﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Web.UI.WebControls;
using log4net;
using System.Text.RegularExpressions;
using System.Data;
using System.Globalization;




/// <summary>
/// Summary description for Utils
/// </summary>
public class Utils 
{
	public Utils()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    /// <summary>
    /// ConvertDateFromDB
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string ConvertDateFromDB(string str)
    {
        try
        {
            DateTime temp = DateTime.Parse(str);
            return temp.ToString("dd/MM/yyyy");
        }
        catch (Exception)
        {
            throw;
        }
    }    

    /// <summary>
    /// ConvertDateTimeFromDB
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string ConvertDateTimeFromDB(string str)
    {
        try
        {
            DateTime temp = DateTime.Parse(str);
            return temp.ToString("dd/MM/yyyy mm:HH");
        }
        catch (Exception)
        {
            throw;
        }
    }

    public static bool IsDate(string dateString, out DateTime dateValue)
    {        
        string[] format=new string[]
        {
            "dd/MM/yyyy",
            "d/M/yyyy",
            "dd/M/yyyy",
            "d/MM/yyyy",
            "dd-MM-yyyy",
            "d-M-yyyy",
            "dd-M-yyyy",
            "d-MM-yyyy"
        };

        if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture,
            DateTimeStyles.None, out dateValue))
        {
            return true;
        }
        return false;
    }

    /// <summary>
    /// IsGuid
    /// </summary>
    /// <param name="candidate"></param>
    /// <returns></returns>
    public static bool IsGuid(string candidate)
    {
        Regex isGuid = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);
        bool isValid = false;
       
        if (candidate != null)
        {
            if (isGuid.IsMatch(candidate))
            {
                isValid = true;
            }
        }
        return isValid;
    }

    /// <summary>
    /// MonthCurrent
    /// </summary>
    /// <returns></returns>
    public static int MonthCurrent()
    {
        return int.Parse(DateTime.Now.Month.ToString().PadLeft(2, '0'));
    }

    /// <summary>
    /// YearCurrent
    /// </summary>
    /// <returns></returns>
    public static int YearCurrent()
    {
        return DateTime.Now.Year;
    }

    /// <summary>
    /// GetNoOfDayInCurrentMonth
    /// </summary>
    /// <returns></returns>
    public static int GetNoOfDayInCurrentMonth()
    {
        return DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
    }

    /// <summary>
    /// NullWrapper
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns>SqlParameter</returns>
    public static SqlParameter NullWrapper(string key,string value){
        if (String.IsNullOrEmpty(value))
            return new SqlParameter(key,DBNull.Value);
	    else
            return new SqlParameter(key,value);
    }

    /// <summary>
    /// DateTimeWrapper
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public static SqlParameter DateTimeWrapper(string key, DateTime value)
    {
        if (value == DateTime.MinValue)
            return new SqlParameter(key, DBNull.Value);
        else
            return new SqlParameter(key, value);
    }

    /// <summary>
    /// StringCurrentDateTime
    /// </summary>
    /// <returns></returns>
    private static string StringCurrentDateTime()
    {
        return DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + "_" +
            DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
    }

    /// <summary>
    /// StringCurrentDate
    /// </summary>
    /// <returns></returns>
    public static string StringCurrentDate()
    {
        string month = DateTime.Now.Month.ToString().PadLeft(2,'0');
        string day = DateTime.Now.Day.ToString().PadLeft(2, '0');
        return day + "/" + month + "/" + DateTime.Now.Year.ToString();
    }

    /// <summary>
    /// UploadFile
    /// </summary>
    /// <param name="fileUpload"></param>
    /// <param name="saveFileName"></param>
    /// <returns></returns>
    public static string UploadFile(FileUpload fileUpload)
    {

        //get directory to save file
        string strPath = HttpContext.Current.Server.MapPath(ConfigurationSettings.AppSettings["DIR_UPLOAD"]);

        //array extension of file allow to upload
        string[] arrExtention = new string[] { "image/jpeg", "image/pjpeg", "image/gif", "image/x-png", "image/png" };

        //get extension of file
        string strFileName = StringCurrentDateTime() + System.IO.Path.GetExtension(fileUpload.FileName);

        #region Command
        ////size of file size , 1/2MB
        //int intFileSize = 1024*1024/2;

        //bool flag = false;

        ////check file size
        //if (fileUpload.PostedFile.ContentLength > intFileSize) { 
        //    return false;
        //}

        ////check extention
        //for (int i = 0; i < arrExtention.Length; i++)
        //{
        //    if (fileUpload.PostedFile.ContentType.Equals(arrExtention[i]))
        //    {
        //        flag= true;
        //    }   
        //} 
        #endregion


        try
        {
            if (fileUpload.HasFile)
            {
                fileUpload.SaveAs(strPath + strFileName);
            }
        }
        catch (Exception)
        {

            throw;
        }

        return strFileName;

    }

    /// <summary>
    /// DeleteFile
    /// </summary>
    /// <param name="fileName">string</param>
    /// <returns>bool</returns>
    public static bool DeleteFile(string fileName)
    {
        bool flag = false;

        // Set full path to file
        string path = HttpContext.Current.Server.MapPath(ConfigurationSettings.AppSettings["DIR_UPLOAD"]);
        FileInfo file = new FileInfo(path + fileName);
        if (file.Exists)
        {
            try
            {
                file.Delete();
                flag = true;
            }
            catch (Exception)
            {
                throw;
            }

        }
        return flag;
    }

    /// <summary>
    /// Encrypt string by md5 method
    /// </summary>
    /// <param name="sPassword"></param>
    /// <returns></returns>
    public static string md5Encrypt(string strTemp)
    {
        System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] bs = System.Text.Encoding.UTF8.GetBytes(strTemp);
        bs = x.ComputeHash(bs);
        System.Text.StringBuilder s = new System.Text.StringBuilder();
        foreach (byte b in bs)
        {
            s.Append(b.ToString("x2").ToLower());
        }
        return s.ToString();
    }

    /// <summary>
    /// GetLimitedWords
    /// </summary>
    /// <param name="str"></param>
    /// <param name="NumberOfWords"></param>
    /// <returns>string</returns>
    public static string GetLimitedWords(string str, int NumberOfWords)
    {
        string[] Words = str.Split(' ');
        string _return = string.Empty;

        if (Words.Length <= NumberOfWords)
        {
            _return = str;
        }
        else
        {
            for (int i = 0; i < NumberOfWords; i++)
            {
                _return += Words.GetValue(i).ToString() + " ";
            }
            _return += "... ";
        }
        return _return;
    }

    /// <summary>
    /// GetEmployeeSession
    /// </summary>
    /// <returns></returns>
    public static Employee GetEmployeeSession()
    {
        Employee emp=null;
        //check session
        if (HttpContext.Current.Session["Employee"] == null)
            HttpContext.Current.Response.Redirect(Constants.LOGIN);

        return (Employee)HttpContext.Current.Session["Employee"];
    }

    /// <summary>
    /// GetEmpCode
    /// </summary>
    /// <param name="maxCode"></param>
    /// <returns></returns>
    public  static string GetEmpCode(string maxCode){
        //string suffixCode = maxCode.Substring(2,8);
        //int code = Int32.Parse(suffixCode)+1;
        //return Constants.PREFIX_EMPCODE + code.ToString().PadLeft(8, '0');
        try
        {
            string sql = "SELECT dbo.ufn_GetEmpCode('C',9)";
            return SqlHelper.ExecuteScalar(CommandType.Text, sql).ToString();
        }
        catch (Exception)
        {
            
            throw;
        }
    }

    /// <summary>
    /// GetEmpCode
    /// </summary>
    /// <param name="maxCode"></param>
    /// <returns></returns>
    public static string GetCusCode(string maxCode)
    {
        //string suffixCode = maxCode.Substring(2,8);
        //int code = Int32.Parse(suffixCode)+1;
        //return Constants.PREFIX_EMPCODE + code.ToString().PadLeft(8, '0');
        try
        {
            string sql = "SELECT dbo.ufn_CustomerCode('C',6)";
            return SqlHelper.ExecuteScalar(CommandType.Text, sql).ToString();
        }
        catch (Exception)
        {

            throw;
        }
    }

    /// <summary>
    /// IsValidTime: Check time format
    /// </summary>
    /// <param name="thetime"></param>
    /// <returns></returns>
    public static bool IsValidTime(string thetime)
    {
        Regex checktime =
         new Regex(@"^(20|21|22|23|[01]d|d)(([:][0-5]d){1,2})$");

        return checktime.IsMatch(thetime);
    }

    public static DateTime DBDate
    {
        get
        {
            string sql = "SELECT GETDATE() AS dbdate";
            object obj= SqlHelper.ExecuteScalar(CommandType.Text, sql, null);
            if (obj == null) return DateTime.Now;
            return Convert.ToDateTime(SqlHelper.CheckDateNull(obj));
        }
    }
  
}